<template>
  <div class="sysuser">
    <!-- 查询表单 -->
    <el-form ref="form" :inline="true" :model="queryParam" :rules="rules" size="mini" style="padding-left: 15px">
      <el-form-item label="供应商：">
        <el-select v-model="queryParam.fltId" filterable clearable width="180px" placeholder="请选择">
          <el-option v-for="(item, index) in supplierList" :key="index" :label="item.fltName" :value="item.uuid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同编号：">
        <el-input v-model="queryParam.contractNo" clearable width="180px" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="金融服务状态：">
        <el-select placeholder="请选择" clearable v-model="queryParam.fsStatus" filterable>
          <el-option v-for="(item, index) in statusList" :key="index" :value="item.rvLowValue" :label="item.rvCmeaning"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item size="mini">
        <el-button type="primary" @click="searchList">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 主表操作按钮 -->
    <div class="btn-area">
      <buttonName @clickEvent="clickEventDom"></buttonName>
    </div>
    <!-- table表单 -->
    <div class="sysuser-table">
      <!-- 主表数据展示 -->
      <div ref="inner" class="inner">
        <el-table
          ref="tableRef"
          :data="mainTableData"
          :header-cell-style="{ textAlign: 'center' }"
          :height="maxHeight"
          border
          highlight-current-row
          style="width: 100%; height: 100%"
          @row-click="rowClick"
        >
          <el-table-column :index="indexMethod" align="center" label="序号" type="index" width="50" fixed="left"></el-table-column>
          <el-table-column align="center" label="状态" prop="fsStatus" show-overflow-tooltip width="100"></el-table-column>
          <el-table-column align="center" label="合同号" prop="contractNo" show-overflow-tooltip width="150">
            <template v-slot="slot">
              <el-tooltip class="item" effect="light" content="跳转到合同" placement="top" :open-delay="3">
                <router-link tag="u" :to="{ name: 'router.dealManage/threedealManage', params: { contractNo: slot.row.contractNo } }">
                  {{ slot.row.contractNo }}
                </router-link>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="签订时间" prop="cmtSigningTime" show-overflow-tooltip width="165"></el-table-column>
          <!--<el-table-column align="center" label="运单编号" prop="wabCode" show-overflow-tooltip width="200"></el-table-column>-->
          <el-table-column align="center" label="供应商名称" prop="fltName" show-overflow-tooltip width="110">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="light" content="详情" placement="top" :open-delay="3">
                <u @click="showDetail(scope.row)">{{ scope.row.fltName }}</u>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="运输单价" prop="cmtTransportUnitPrice" show-overflow-tooltip width="130"></el-table-column>
          <el-table-column align="center" label="运输吨数" prop="cmtContractTotalTransport" show-overflow-tooltip width="100"></el-table-column>
          <el-table-column align="center" label="总金额" prop="wabAmount" show-overflow-tooltip width="100"></el-table-column>
          <el-table-column align="center" label="承运起始日期" prop="cmtStartDateShipment" show-overflow-tooltip width="130"></el-table-column>
          <!--<el-table-column align="center" label="运单完成时间" prop="wabCompleteTime" show-overflow-tooltip width="200"></el-table-column>-->
          <el-table-column align="center" label="结算金额" prop="fsAmount" show-overflow-tooltip width="100"></el-table-column>
          <el-table-column align="center" label="结算时间" prop="fsSettlementTime" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="放款时间" prop="fsLoanTime" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="利息" prop="fsInterest" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="审核意见" prop="fsAuditOpinion" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        ref="pagination"
        :current-page="Pagination.currentPage"
        :layout="Pagination.layout"
        :page-size="Pagination.PageSize"
        :page-sizes="Pagination.pageSizeList"
        :total="Pagination.total"
        background
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <el-dialog
      ref="dialog"
      v-el-drag-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="fullInfoDialog.show"
      :title="fullInfoDialog.title"
      width="1200px"
      @close="close"
    >
      <div class="full-info-form">
        <div class="full-info-form-item">供应商信息</div>
        <el-form :model="fullInfo" label-width="14rem" size="mini" label-position="right" ref="fullInfoFormInfo" :rules="fullInfoRules">
          <el-row align="center">
            <el-col :span="8">
              <el-form-item label="供应商名称：" prop="fltName">
                <el-input disabled v-model="fullInfo.fltName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业地址：" prop="fltName">
                <el-input disabled v-model="fullInfo.fltAddress"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业电话：" prop="fltName">
                <el-input disabled v-model="fullInfo.fltLinkphone"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row align="center">
            <el-col :span="8">
              <el-form-item label="法人身份证姓名：" prop="fltName">
                <el-input disabled v-model="fullInfo.cltCliLegalname"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法人身份证号：" prop="fltName">
                <el-input disabled v-model="fullInfo.cltCliLegalid"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人：" prop="fltName">
                <el-input disabled v-model="fullInfo.fltContact"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row align="center">
            <el-col :span="8">
              <el-form-item label="联系人电话：" prop="fltName">
                <el-input disabled v-model="fullInfo.fltContactPhone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照注册号：" prop="fltName">
                <el-input disabled v-model="fullInfo.cltRegistorno"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户行：" prop="fltName">
                <el-input disabled v-model="fullInfo.fltBank"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row align="center">
            <el-col :span="8">
              <el-form-item label="银行账号：" prop="fltName">
                <el-input disabled v-model="fullInfo.fltAccount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总金额：" prop="wabAmount">
                <el-input disabled v-model="fullInfo.wabAmount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结算金额：" prop="fsAmount">
                <el-input
                  v-model="fullInfo.fsAmount"
                  :disabled="fullInfoDialog.currentStatus === fullInfoDialogStatus.view"
                  placeholder="请输入结算金额"
                  clearable
                  maxLength="10"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row align="center">
            <el-col :span="8">
              <el-form-item label="结算时间：" prop="fsSettlementTime">
                <el-date-picker
                  format="yyyy年MM月dd日"
                  v-model="fullInfo.fsSettlementTime"
                  :disabled="fullInfoDialog.currentStatus === fullInfoDialogStatus.view"
                  :picker-options="fsSettlementTimeOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="放款时间：" prop="fsLoanTime">
                <el-date-picker
                  format="yyyy年MM月dd日"
                  v-model="fullInfo.fsLoanTime"
                  :disabled="fullInfoDialog.currentStatus === fullInfoDialogStatus.view"
                  :picker-options="fsLoanTimeOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="利息：" prop="fsInterest">
                <el-input v-model="fullInfo.fsInterest" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="full-info-form" style="margin-top: 30px">
        <div class="full-info-form-item">附件列表</div>
        <el-table :data="annexFileList" border>
          <el-table-column align="center" label="序号" type="index" width="55"></el-table-column>
          <el-table-column align="center" label="文件" prop="aName" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="操作" show-overflow-tooltip width="55">
            <template slot-scope="scope">
              <el-button circle size="mini" type="primary" @click="downFile(scope.row)" icon="el-icon-download"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            ref="pagination"
            :current-page="fullInfoDialog.fileIndex"
            :layout="Pagination.layout"
            :page-size="fullInfoDialog.fileSize"
            :page-sizes="[5, 10, 15]"
            :total="fullInfoDialog.fileTotal"
            background
            small
            @size-change="updateFileSize"
            @current-change="updateFileIndex"
          ></el-pagination>
        </div>
      </div>
      <div class="full-info-form" style="margin-top: 30px">
        <div class="full-info-form-item">审核意见</div>
        <el-form v-model="fullInfo" size="mini">
          <el-form-item prop="fsAuditOpinion">
            <el-input
              type="textarea"
              v-model="fullInfo.fsAuditOpinion"
              placeholder="请输入审核意见"
              show-word-limit
              :autosize="{ minRows: 2, maxRows: 6 }"
              maxlength="280"
              :disabled="fullInfoDialog.isShowDetail"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="fullInfoDialog.show = false">关闭</el-button>
        <el-button v-show="!fullInfoDialog.isShowDetail" size="mini" type="danger" @click="doReview('SHJJ')">拒 绝</el-button>
        <el-button v-show="!fullInfoDialog.isShowDetail" size="mini" type="primary" @click="doReview('TG')">通 过</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getRefCodesByType } from '@/request/api'
import isAuth from '@/mixins/buttonAuth'
import paginationMixin from '@/mixins/pagination'
import { financialList } from '@/request/supplierManagement/SupplierMaintenance'
import buttonName from '@/components/buttonName/button-name'
import { GYSClientList } from '@/request/dropDown'
import financialService from '@/request/cstManagement/financialService'

export default {
  name: 'router.SupplierMaintenance',
  mixins: [paginationMixin, isAuth],
  data() {
    const fsSettlementTimeValidator = (rule, val, callback) => {
      if (val) {
        const other = this.fullInfo.fsLoanTime
        if (other && other.getTime() === val.getTime()) {
          callback(new Error('不能跟放款时间相同'))
          return
        }
        callback()
        return
      }
      callback(new Error('请输入结算时间'))
    }
    const fsLoanTimeValidator = (rule, val, callback) => {
      if (val) {
        const other = this.fullInfo.fsSettlementTime
        if (other && other.getTime() === val.getTime()) {
          callback(new Error('不能跟结算时间相同'))
          return
        }
        callback()
        return
      }
      callback(new Error('请输入放款时间'))
    }
    const fsSettlementTimeOptions = {
      disabledDate: time => {
        if (this.fullInfo.fsLoanTime) {
          return time.getTime() <= this.fullInfo.fsLoanTime.getTime()
        }
        return false
      },
    }
    const fsLoanTimeOptions = {
      disabledDate: time => {
        if (this.fullInfo.fsSettlementTime) {
          return time.getTime() >= this.fullInfo.fsSettlementTime.getTime()
        }
        return false
      },
    }
    return {
      fsSettlementTimeOptions,
      fsLoanTimeOptions,
      fullInfoRules: {
        fsAmount: [{ required: true, message: '请输入结算金额', trigger: 'blur' }],
        fsSettlementTime: [{ required: true, validator: fsSettlementTimeValidator, trigger: ['blur', 'change'] }],
        fsLoanTime: [{ required: true, validator: fsLoanTimeValidator, trigger: ['blur', 'change'] }],
      },
      currentRow: {},
      fullInfoDialogStatus: {
        edit: 'edit',
        view: 'view',
      },
      supplierList: [], // 供应商列表
      statusList: [], // 金融服务状态列表
      queryParam: {
        fsStatus: '', // 金融服务状态
        contractNo: '', // 合同编号
        fltId: '', // 供应商
      },
      //表格数据
      mainTableData: [],
      //选中行数据
      selectData: [],
      fullInfoDialog: {
        show: false,
        title: '详细信息',
        fileIndex: 1,
        fileSize: 5,
        fileTotal: 0,
        isShowDetail: false,
        currentStatus: '',
      },
      maxHeight: 700,
      fullInfo: {
        fltName: '',
        fltAddress: '',
        fltLinkphone: '',
        cltCliLegalname: '',
        cltCliLegalid: '',
        fltContact: '',
        fltContactPhone: '',
        cltRegistorno: '',
        fltBank: '',
        fltAccount: '',
        fsAuditOpinion: '',
        wabAmount: 0,
        fsSettlementTime: null,
        fsLoanTime: null,
        fsInterest: 0,
        fsAmount: 0,
      },
      annexFileList: [], // 附件列表
    }
  },
  watch: {
    fullInfo: {
      deep: true,
      handler(val) {
        // 提前结算金额*8%*（合同约定结算日期-放款时间）/360
        if (val.fsAmount && val.fsLoanTime && val.fsSettlementTime && val.fsLoanTime.getTime() !== val.fsSettlementTime.getTime()) {
          const days = (val.fsSettlementTime.getTime() - val.fsLoanTime.getTime()) / (1000 * 60 * 60 * 24)
          this.fullInfo.fsInterest = Math.round(((val.fsAmount * 100) / 8).accMul(days / 360) * 100) / 100
        } else {
          this.fullInfo.fsInterest = 0
        }
      },
    },
  },
  components: {
    buttonName,
  },
  created() {
    this.refreshList()
    this.getStatusList()
    this.getSupplierList()
  },
  methods: {
    getStatusList() {
      getRefCodesByType('金融服务状态').then(res => {
        this.statusList = res.data
      })
    },
    getSupplierList() {
      GYSClientList({}).then(res => {
        this.supplierList = res.data
      })
    },
    getAnnexFileList() {
      financialService
        .queryAnnexArray({
          annex: [
            {
              aPubId: this.currentRow.fsId,
              aModule: 'JR',
            },
          ],
          index: this.fullInfoDialog.fileIndex,
          size: this.fullInfoDialog.fileSize,
        })
        .then(res => {
          this.annexFileList = res.data
          this.fullInfoDialog.fileTotal = res.total
        })
    },
    clickEventDom({ mdlCode }) {
      if (mdlCode === 'review') {
        this.review()
      }
      if (mdlCode === 'unReview') {
        this.unReview()
      }
    },
    review() {
      if (!Object.keys(this.currentRow).length) {
        this.$message.error({
          showClose: true,
          message: '至少选择一项',
        })
        return
      }
      if (this.currentRow.fsStatusCode !== 'YTJ') {
        this.$message.error({
          showClose: true,
          message: '请选择已提交的数据',
        })
        return
      }
      // const id = this.selectData[0].uuid
      // for (let item of this.selectData) {
      //   if (item.uuid !== id) {
      //     this.$message.error({
      //       showClose: false,
      //       message: '请选择同一个供应商'
      //     })
      //     return
      //   }
      //   if (item.fsStatusCode !== 'YTJ') {
      //     this.$message.error({
      //       showClose: false,
      //       message: '请选择已提交的数据'
      //     })
      //     return
      //   }
      // }
      this.fullInfoDialog.currentStatus = 'edit'
      this.fullInfo = this.currentRow
      this.fullInfoDialog.show = true
      this.getAnnexFileList()
    },
    doReview(status) {
      if (status === 'TG') {
        this.$refs.fullInfoFormInfo.validate(validate => {
          if (validate) {
            financialService
              .review(
                Object.assign(
                  {
                    status,
                    ids: [this.currentRow.fsId],
                  },
                  this.fullInfo
                )
              )
              .then(() => {
                this.$message.success({
                  showClose: true,
                  message: '成功',
                })
                this.fullInfoDialog.show = false
              })
          }
        })
      } else {
        financialService
          .review(
            Object.assign(
              {
                status,
                ids: [this.currentRow.fsId],
              },
              this.fullInfo
            )
          )
          .then(() => {
            this.$message.success({
              showClose: true,
              message: '成功',
            })
            this.fullInfoDialog.show = false
          })
      }
    },
    unReview() {
      if (!this.selectData.length) {
        this.$message.error({
          showClose: true,
          message: '至少选择一项',
        })
        return
      }
      for (let item of this.selectData) {
        if (item.fsStatusCode !== 'SHJJ' && item.fsStatusCode !== 'TG') {
          this.$message.error({
            showClose: true,
            message: `${item.contractNo}不是审核通过或者审核拒绝状态，无法取消`,
          })
          return
        }
      }
      financialService
        .review(
          Object.assign(
            {
              ids: [this.currentRow.fsId],
              status: 'YTJ',
            },
            this.fullInfo
          )
        )
        .then(() => {
          this.$message.success('取消成功')
          this.refreshList()
        })
    },
    getList(currentPage, pageSize, updateTotal) {
      financialList({
        fltId: this.queryParam.fltId,
        contractNo: this.queryParam.contractNo,
        fsStatus: this.queryParam.fsStatus,
        PageIndex: this.Pagination.currentPage,
        PageSize: this.Pagination.pageSize,
      }).then(response => {
        this.mainTableData = response.data
        updateTotal(Number(response.total))
        this.selectData = []
        this.$refs['tableRef'].clearSelection()
      })
    },
    rowClick(row) {
      this.currentRow = row
      // this.$refs['tableRef'].toggleRowSelection(row)
    },
    close() {
      this.fullInfoDialog.isShowDetail = false
      this.annexFileList = []
      this.$refs.fullInfoFormInfo.resetFields()
      this.refreshList()
    },
    downFile(file) {
      const a = document.createElement('a')
      a.download = file.aName
      if (process.env.NODE_ENV === 'development') {
        a.href = `/${window._$api.PROXYURL}${file.aPath}`
      } else {
        a.href = file.aPath
      }
      a.click()
      document.removeChild(a)
    },
    tableSelectChangeHandler(val) {
      this.selectData = val
    },
    updateFileSize(val) {
      this.fullInfoDialog.fileSize = val
      this.getAnnexFileList()
    },
    updateFileIndex(val) {
      this.fullInfoDialog.fileIndex = val
      this.getAnnexFileList()
    },
    showDetail(row) {
      if (this.selectData.length) {
        const id = row.uuid
        const no = row.cmtContractNo
        let inArray = false
        for (let item of this.selectData) {
          if (item.uuid !== id) {
            this.$message.error({
              showClose: false,
              message: '请选择同一个供应商',
            })
            return
          }
          if (!inArray) {
            inArray = no === item.cmtContractNo
          }
        }
        if (!inArray) {
          this.selectData.push(row)
        }
      } else {
        this.selectData = []
        this.selectData.push(row)
      }
      this.fullInfoDialog.currentStatus = 'view'
      this.fullInfo = row
      console.log(this.fullInfo)
      this.fullInfoDialog.show = true
      this.fullInfoDialog.isShowDetail = true
      this.getAnnexFileList()
    },
  },
}
</script>
<style lang="scss" scoped>
.full-info-form {
  position: relative;
  border: 3px solid rgb(144, 144, 144);
  padding: 20px 10px;

  .full-info-form-item {
    font-size: 18px;
    position: absolute;
    top: -14px;
    left: 20px;
    background: white;
    width: 100px;
    text-align: center;
  }
}

.pingfen {
  .tableBox {
    padding: 10px 20px;

    .buttonBox {
      height: 100px;
      line-height: 100px;
      text-align: center;

      button {
        width: 150px;
        height: 45px;
        background-color: #169bd5;
        cursor: pointer;
        color: #fff;
        font-size: 20px;
      }
    }

    .remark {
      p {
        font-size: 15px;
      }
    }
  }
}

.tableHead {
  font-size: 18px;
  letter-spacing: 3px;
}

.sysuser {
  padding-top: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .btn-area {
    padding-bottom: 15px;
    padding-left: 15px;
  }

  .sysuser-table {
    padding: 0 15px;
    flex: 1;
    // min-height: 300px;
    // display:flex;
    // flex-direction: column;
    // justify-items: space-between;
    .inner {
      height: 100%;
      box-sizing: border-box;
    }
  }

  .block {
    padding-bottom: 5px;
    padding-right: 15px;
  }
}

.tu1 {
  position: relative;

  img {
    position: absolute;
    top: 50px;
    left: 10px;
  }
}

.tu2 {
  position: relative;

  img {
    position: absolute;
    top: 50px;
    left: 10px;
  }
}

.tu3 {
  position: relative;

  img {
    position: absolute;
    top: 50px;
    left: 10px;
  }
}
</style>
